package com.zbkj.service.manager.impl;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbkj.dal.base.constants.SysConfigConstants;
import com.zbkj.dal.base.enums.BizImgTypeEnums;
import com.zbkj.dal.base.enums.BooleanEnums;
import com.zbkj.dal.base.enums.QrcodeTypeEnums;
import com.zbkj.dal.config.CrmebConfig;
import com.zbkj.dal.dao.QrcodeBusinessDao;
import com.zbkj.dal.dao.QrcodeDao;
import com.zbkj.dal.entity.qrcode.Qrcode;
import com.zbkj.dal.entity.qrcode.QrcodeBusiness;
import com.zbkj.dal.entity.system.SystemAttachment;
import com.zbkj.dal.pojo.vo.CloudVo;
import com.zbkj.dal.pojo.vo.FileResultVo;
import com.zbkj.service.manager.WechatManager;
import com.zbkj.service.service.SystemConfigService;
import com.zbkj.service.service.impl.OssServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
public class WechatManagerImpl implements WechatManager {

    @Value("${wx.miniapp.env-version}")
    private String envVersion;

    @Value("${wx.miniapp.qrcodePath}")
    private String qrcodePath;

    @Resource
    private QrcodeDao qrcodeDao;

    @Resource
    private QrcodeBusinessDao qrcodeBusinessDao;

    @Resource
    private WxMaQrcodeService wxMaQrcodeService;

    @Resource
    private OssServiceImpl ossService;


    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private CrmebConfig crmebConfig;

    private static final Logger logger = LoggerFactory.getLogger(WechatManagerImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getQrcodePath(QrcodeTypeEnums qrcodeType, String ownerCode, String businessUrl) {

        // 查询是否存在
        LambdaQueryWrapper<QrcodeBusiness> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QrcodeBusiness::getQrcodeType, qrcodeType);
        wrapper.eq(QrcodeBusiness::getOwnerCode, ownerCode);
        QrcodeBusiness qrcodeBusiness = qrcodeBusinessDao.selectOne(wrapper);
        if (Objects.nonNull(qrcodeBusiness)) {
            LambdaQueryWrapper<Qrcode> qrcodeWrapper = new LambdaQueryWrapper<>();
            qrcodeWrapper.eq(Qrcode::getScene, qrcodeBusiness.getScene());
            Qrcode qrcode = qrcodeDao.selectOne(qrcodeWrapper);
            logger.info("qrcode>>>{}", JSON.toJSONString(qrcode));
            return qrcode.getFilePath();
        }
        return generateSunQrcode(qrcodeType, ownerCode, businessUrl);
    }

    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public String generateSunQrcode(QrcodeTypeEnums qrcodeType, String ownerCode, String businessUrl) {
        // 生成太阳码图片
        String scene = qrcodeType.generateScene(ownerCode);
        byte[] wxQrcodeBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(scene, "pages/index/index", false, envVersion, 450, true, null, true);

        String ossPath = String.format("%s/%s.jpg", BizImgTypeEnums.QRCODE_IMAGE.getBasePath(), scene);

        Qrcode qrcode = new Qrcode();
        qrcode.setScene(scene);
        qrcode.setFilePath(ossPath);
        qrcode.setStatus(BooleanEnums.TRUE.getCode());
        qrcode.setDeleted(BooleanEnums.FALSE.getCode());
        qrcode.setUserId(Integer.valueOf(ownerCode));
        qrcodeDao.insert(qrcode);

        //图片上传到阿里云
        SystemAttachment systemAttachment = new SystemAttachment();

        systemAttachment.setImageType(3);
        systemAttachment.setSattDir("crmebimage/sxwxapp/static/images/qrcode/" + scene + ".jpg");
        CloudVo cloudVo = new CloudVo();
        cloudVo.setDomain(systemConfigService.getValueByKeyException(SysConfigConstants.CONFIG_AL_UPLOAD_URL));
        cloudVo.setAccessKey(systemConfigService.getValueByKeyException(SysConfigConstants.CONFIG_AL_ACCESS_KEY));
        cloudVo.setSecretKey(systemConfigService.getValueByKeyException(SysConfigConstants.CONFIG_AL_SECRET_KEY));
        cloudVo.setBucketName(systemConfigService.getValueByKeyException(SysConfigConstants.CONFIG_AL_STORAGE_NAME));
        cloudVo.setRegion(systemConfigService.getValueByKeyException(SysConfigConstants.CONFIG_AL_STORAGE_REGION));
        // 保存路径
        String savePath = qrcodePath + "/" + scene + ".jpg";
        File file = new File(savePath); // 要写入的文件

        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(wxQrcodeBytes); // 将字节数组写入文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        String webPathQn = crmebConfig.getImagePath();
        try {
            logger.info("AsyncServiceImpl.oss.id " + systemAttachment.getSattDir());
            logger.info("cloudVo>>>>>>>{}", JSON.toJSONString(cloudVo));
            ossService.upload(cloudVo, systemAttachment.getSattDir(), webPathQn + "/" + systemAttachment.getSattDir(), file);
        } catch (Exception e) {
            logger.error("AsyncServiceImpl.oss fail " + e.getMessage());
        }

        QrcodeBusiness qrcodeBusiness = new QrcodeBusiness();
        qrcodeBusiness.setScene(scene);
        qrcodeBusiness.setQrcodeType(qrcodeType.getCode());
        qrcodeBusiness.setOwnerCode(ownerCode);
        qrcodeBusiness.setBusinessUrl(businessUrl);
        qrcodeBusiness.setStatus(BooleanEnums.TRUE.getCode());
        qrcodeBusiness.setDeleted(BooleanEnums.FALSE.getCode());
        qrcodeBusinessDao.insert(qrcodeBusiness);

        return qrcode.getFilePath();
    }

}
